package org.jadelyre.core.task;

import org.jadelyre.core.Channel;
import org.jadelyre.core.WriteCompletionHandler;
import org.jadelyre.core.codec.Packet;
import org.jadelyre.core.exception.CodecException;
import org.jadelyre.core.exception.JadelyreException;
import org.jadelyre.core.worker.Worker;

import java.nio.ByteBuffer;

public class SendTask extends ChannelTask<Packet> {

    public SendTask(Channel channel, Worker<Packet> worker) {
        super(channel, worker);
//        executor = channel.getJadeLyre().getWorkerFactory().getWriteWorker();
    }

    @Override
    protected <T> void work(T t) throws CodecException {
        Packet packet = (Packet) t;
        sendPacket(packet);
    }

    private void sendPacket(Packet packet) throws CodecException {
        ByteBuffer byteBuffer = channel.getJadeLyre().getCodec().encode(packet);
        byteBuffer.order(Packet.BYTE_ORDER);
        sendByteBuffer(byteBuffer);
    }

    private void sendByteBuffer(ByteBuffer byteBuffer){
        WriteCompletionHandler writeCompletionHandler = channel.getWriteCompletionHandler();
        try {
            writeCompletionHandler.getSemaphore().acquire();
        } catch (InterruptedException e) {
            throw new JadelyreException(e);
        }
        writeCompletionHandler.getAsynchronousSocketChannel().
                write(byteBuffer,channel,writeCompletionHandler.setWriteByteBuffer(byteBuffer));
    }
}
